package com.caiyi.financial.nirvana.sms.shiro;

import com.caiyi.financial.nirvana.sms.entity.SmsAdmin;
import com.caiyi.financial.nirvana.sms.entity.SmsRole;
import com.caiyi.financial.nirvana.sms.service.SmsAdminService;
import com.caiyi.financial.nirvana.sms.service.SmsRoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SmsShiroRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SmsAdminService adminService;
    @Autowired
    private SmsRoleService roleService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String account = (String) token.getPrincipal();
        logger.info(account + "正在进行登录认证");
        SmsAdmin user = adminService.selectByAccount(account);
        if (user == null) {
            logger.info(account + "登录认证失败");
            return null;
        }
        logger.info(account + "登录认证成功");
        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        SmsAdmin user = (SmsAdmin) principals.getPrimaryPrincipal();
        SmsRole role = new SmsRole();
        role.setId(user.getRoleId());
        role = roleService.selectByPrimaryKey(role);
        authorizationInfo.addRole(role.getName());
        return authorizationInfo;
    }
}
